<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}渠道货态`"
    width="936"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[460px]" v-loading="loading">
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
        :originOption="optionsData"
      >
      </VForm>
      <AddOptions
        ref="detailRef"
        :apiCargoStatus="apiCargoStatus"
        :data="detailData"
      />
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'
import AddOptions from './AddOptions/index.vue'

import {
  createCargoStatus,
  updateCargoStatus,
  cargoStatusDetail,
  getLogisticsChannel,
  getLogisticsApi,
} from '../api'

const props = defineProps({
  id: { type: [String, Number], default: '' },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  inline: true,
  labelPosition: 'top',
}

const rules = {
  logistics_id: [{ required: true, message: '请选择物流商', trigger: 'blur' }],
  channel_id: [
    { required: true, message: '请选择物流商渠道', trigger: 'blur' },
  ],
  channel_api_id: [
    { required: true, message: '请选择渠道API', trigger: 'blur' },
  ],
}

const form = ref()
const detailRef = ref()
const model = ref({
  channel_id: '',
})
const loading = ref()
const detailData = ref()
const optionsData = ref({})
const apiCargoStatus = ref([])

const handleChangeLogistics = e => {
  getChanel(e)
}

const getChanel = async logistics_id => {
  const formValues = await form.value.getFormValues()
  try {
    if (!formValues?.logistics_id) {
      optionsData.value['channel'] = []
      return
    }
    const { data } = await getLogisticsChannel({ logistics_id })
    optionsData.value['channel'] = data
  } catch (e) {
    console.error(e)
  } finally {
    optionsData.value['logistics_api'] = []
    model.value = Object.assign({}, formValues, {
      channel_id: '',
      channel_api_id: '',
    })
    apiCargoStatus.value = []
  }
}

const handleChangeChannel = async channel_id => {
  const formValues = await form.value.getFormValues()
  try {
    if (!channel_id || !formValues?.logistics_id) {
      optionsData.value['logistics_api'] = []
      return
    }
    const { data } = await getLogisticsApi({
      channel_id,
      logistics_id: formValues.logistics_id,
    })
    optionsData.value['logistics_api'] = data
  } catch (e) {
    console.error(e)
  } finally {
    apiCargoStatus.value = []
    model.value = Object.assign({}, formValues, { channel_api_id: '' })
  }
}

const handleChangeLogisticsApi = e => {
  const _data = optionsData.value['logistics_api']
  const _item = _data.find(n => n.logistics_api_id === e)

  if (_item && _item.api_cargo_status) {
    apiCargoStatus.value = _item.api_cargo_status
  } else {
    apiCargoStatus.value = []
  }
}

const publicStyle = { style: { width: '262px' } }
const fieldList = [
  { type: 'title', label: '基础信息' },
  {
    field: 'logistics_id',
    label: '物流商名称',
    ...publicStyle,
    type: 'select',
    options: {
      labelKey: 'logistics_name',
      valueKey: 'logistics_id',
    },
    origin: 'map.logistics',
    itemProps: {
      onChange: handleChangeLogistics,
    },
  },
  {
    field: 'channel_id',
    label: '物流商渠道中文名称',
    ...publicStyle,
    type: 'select',
    options: {
      labelKey: 'channel_name',
      valueKey: 'channel_id',
    },
    originField: 'channel',
    itemProps: {
      onChange: handleChangeChannel,
    },
  },
  {
    field: 'channel_api_id',
    label: '渠道API名称',
    ...publicStyle,
    type: 'select',
    options: {
      labelKey: 'api_name',
      valueKey: 'logistics_api_id',
    },
    originField: 'logistics_api',
    itemProps: {
      onChange: handleChangeLogisticsApi,
    },
  },
  {
    field: 'remark',
    label: '备注',
    type: 'textarea',
    full: true,
    itemStyle: { width: '100%' },
    autosize: { minRows: 4, maxRows: 8 },
  },
]

watch(
  () => props.id,
  val => {
    nextTick(() => {
      if (val) getDetail(val)
    })
  }
)

const getDetail = async id => {
  try {
    loading.value = true
    const { data } = await cargoStatusDetail({ id })
    const { logistics_id, channel_id, channel_api_id, details } = data
    model.value = {
      ...data,
    }
    await nextTick()
    await getChanel(logistics_id)
    await handleChangeChannel(channel_id)
    await handleChangeLogisticsApi(channel_api_id)
    model.value = {
      ...data,
    }
    detailData.value = details
  } catch (e) {
    detailData.value = []
    console.error(e)
  } finally {
    loading.value = false
  }
}

const isEdit = computed(() => {
  return !!props.id
})

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit()
    const api = {
      edit: updateCargoStatus,
      add: createCargoStatus,
    }
    const { id } = props
    const detailData = await detailRef.value.submitForm()
    const { code, message } = await api[isEdit.value ? 'edit' : 'add']({
      id: id || undefined,
      ...formInfo,
      details: detailData?.details,
    })
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success(isEdit.value ? '修改成功' : '保存成功')
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  model.value = {}
  await nextTick()
  form.value.resetForm()
  detailRef.value.resetForm()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
